function setTimer(id, type, __id__) {
    if (globalThis.timers == undefined) {
        globalThis.timers = {}
    }
    globalThis.timers[__id__] = {
        id: id,
        type: type
    };
}

function clearTimer(__id__) {
    if (globalThis.timers == undefined) throw new Error("globalThis timers is undefined");

    var ins = globalThis.timers[__id__];
    if (ins.type == "timeout") {
        clearTimeout(ins.id);
    } else if (ins.type == "interval") {
        clearInterval(ins.id);
    } else {
        throw new Error("undefined timer type");
    }
}

module.exports = {
    close: function(id, __id__) {
        var instance = globalThis.eventbus.getInstance(__id__);
        if (instance != undefined) {
            globalThis.eventbus.detach(instance);
        }
        clearTimer(__id__);
    },
    setTimeout: function(id, __id__, timeout) {
        console.log("****** @native.timer.js setTimeout ******")
        console.log(id, __id__, timeout)
        var t = setTimeout(function() {
            globalThis.eventbus.emit(__id__, "timeout", []);
        }, timeout);
        setTimer(t, "timeout", __id__);
    },
    setInterval: function(id, __id__, timeout) {
        console.log("****** @native.timer.js setInterval ******")
        console.log(id, __id__, timeout)
        setInterval(function() {
            globalThis.eventbus.emit(__id__, "interval", []);
        }, timeout);
        setTimer(t, "interval", __id__);
    }
}